#include "std.h"
#include "stm8s_adc1.h"
#include "config.h"
#include "motor.h"
#include "es_pwm30.h"



void Init_Timer1(void);
void NVIC_Config(void);
void TIM4_Init(void);
void ADC_Config(void);



void init()
{
    RCC_Config();
    NVIC_Config();
    GPIO_Config();
    UART1_Config();
    //ADC_Config();

    //TIM4(作SysTick)
    TIM4_Init();

    //PWM初始化
    pwm_InitChannel(s1,PWM_MODE_MOTOR);
    pwm_SetChannel(s1,32000);
    pwm_InitChannel(s2,PWM_MODE_MOTOR);
    pwm_SetChannel(s2,32000);

    EXTI_Config();
}





u8 ins=0;        //为1时增长
u16 val=0;

void loop()
{    
    //电机循环
   motor_loop();   
   //stop();

    delay(1);
}


void GPIO_Config()
{   
    //GPIO_Init(GPIOD,GPIO_PIN_4,GPIO_MODE_OUT_PP_HIGH_FAST);
    //GPIO_Init(GPIOA,GPIO_PIN_1,GPIO_MODE_OUT_PP_HIGH_FAST);

	GPIO_Init(POS_1_PORT,POS_1_PIN, GPIO_MODE_IN_PU_NO_IT);
    GPIO_Init(POS_2_PORT,POS_2_PIN, GPIO_MODE_IN_PU_NO_IT);
    
    GPIO_Init(KEY_1_PORT, KEY_1_PIN, GPIO_MODE_IN_FL_IT);
    GPIO_Init(KEY_2_PORT, KEY_2_PIN, GPIO_MODE_IN_FL_IT);    
}

void NVIC_Config()
{
    //中断优先级控制(数字大的优先)
    NVIC_Control(12, 3); //12 14是CC中断
    NVIC_Control(14, 3);
    NVIC_Control(4, 1); //4 6是PB PD EXTI中断
    NVIC_Control(5, 1); 
    NVIC_Control(6, 1);

    NVIC_Control(23, 1);    //降低TIM4优先级(systick)    
}

void TIM4_Init()
{
    TIM4_TimeBaseInit(TIM4_PRESCALER_128, 250); //systick 2ms
    TIM4_ClearFlag(TIM4_FLAG_UPDATE);
    TIM4_ITConfig(TIM4_IT_UPDATE, ENABLE);
    TIM4_Cmd(ENABLE);
}

void EXTI_Config()
{
    //中断,仅下降沿触发
    EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOC, EXTI_SENSITIVITY_FALL_ONLY);
    
    enableInterrupts(); //开启中断
}




u16 GetAdc4Value(void){
    //配置通道4(AIN4)
	//单次转换
	ADC1_ConversionConfig(ADC1_CONVERSIONMODE_SINGLE, ADC1_CHANNEL_4, ADC1_ALIGN_RIGHT);    
	
	//开始转换
	ADC1_StartConversion();
	
	//等待转换完成
	while(ADC1_GetFlagStatus(ADC1_FLAG_EOC) == RESET); 
	
	//获取AD值
	return ADC1_GetConversionValue();
}


void ADC_Config(){
	//重新初始化
	ADC1_DeInit();	
	
	//单次转换模式(由循环读取ad值)
	//通道4 
	//2分频
	//内部定时器1的TRG事件
	//内部定时器1的TRG事件-关闭
	//数据右对齐 
	//通道4施密特触发器
	//通道4施密特触发器-开启
	ADC1_Init(ADC1_CONVERSIONMODE_SINGLE, ADC1_CHANNEL_4, ADC1_PRESSEL_FCPU_D2, ADC1_EXTTRIG_TIM, DISABLE, ADC1_ALIGN_RIGHT, ADC1_SCHMITTTRIG_CHANNEL4, ENABLE);
	
	//启动ADC1
	ADC1_Cmd(ENABLE);
}





#ifdef USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval : None
  */
void assert_failed(u8 *file, u32 line)
{
    /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

    /* Infinite loop */
    while (1)
    {
    }
}
#endif

/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
